package com.wtwd.campus.utils;


import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;


/**
 * @Author ldaoliang
 * @Date 2020/2/17
 * 做Http请求工具类
 */
public class HttpUtil {

    /**
     * Http get请求 高德api调用
     *
     * @param url
     * @return
     */
    public static String gaoDeApiGet(String url, Map<String, String> map) {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String result = "";
        CloseableHttpResponse response = null;
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            // 请求参数相关  问号拼接
            List<NameValuePair> list = new LinkedList<>();  //请求参数集合
            // 遍历map
            Set set = map.keySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next().toString();
                BasicNameValuePair param = new BasicNameValuePair(key, map.get(key));
                list.add(param);
            }
            uriBuilder.setParameters(list);
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            // 获取执行结果
            response = httpClient.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();
            result = EntityUtils.toString(httpEntity);
            System.out.println(result);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}
